# 利用面向对象思想实现搜索引擎
class SearchEngineBase:
    def __init__(self):
        pass
    
    # 搜索器
    def add_corpus(self, file_path):
        with open(file_path, "rb") as fin:
            text = fin.read().decode("utf-8")
        self.process_corpus(file_path, text)
    
    # 索引器
    def process_corpus(self, id, text):
        raise Exception("process_corpus not implemented.")
    
    # 检索器
    def search(self, query):
        raise Exception("search not implemented.")

# 用户接口
def main(search_engine):
    for file_path in ["../files/1.txt", "../files/2.txt", "../files/3.txt", "../files/4.txt", "../files/5.txt"]:
        search_engine.add_corpus(file_path)
    
    while True:
        query = input("请输入要搜索的内容：")
        if "quit" == query or "exit" == query:
            print("程序即将退出，再见！")
            break
        results = search_engine.search(query)
        print("found {} result(s):".format(len(results)))
        for result in results:
            print(result)

class SimpleEngine(SearchEngineBase):
    def __init__(self):
        super(SimpleEngine, self).__init__()
        # 建立索引时使用
        self.__id_to_texts = {}
        
    def process_corpus(self, id, text):
        # 以文件路径为键，文件内容为值，形成键值对，存储在字典中，建立索引
        self.__id_to_texts[id] = text
    
    def search(self, query):
        results = []
        # 依次检索字典中的键值对，如果文件内容包含用户要搜索的信息，则将此文件的文件路径存储在 results 列表中
        for id, text in self.__id_to_texts.items():
            if query in text:
                results.append(id)
        return results

search_engine = SimpleEngine()
main(search_engine)
